<template>
  <view>
    <view style="padding-bottom: 30rpx;">

      <view class="color-box" :style="'background: url(' +  imgpath + 'luyi/unit/2023/11/01/3011.png);'">
        <view class="img-box" @click="changeimage">
          <image :src="imagesrc"></image>
        </view>
        <view class="titilename">{{username}}</view>
        <view class="titilephone">{{userphone}}</view>
      </view>

      <view class="info-pos">
        <view class="base-info">基本信息填写</view>
        <view class="info1">
          <input v-model="username" disabled="true" placeholder="上传身份证获取姓名" style="font-size: 14px;" />
        </view>
        <view class="info2">
          <!-- <view class="info-box">上传身份证获取性别</view> -->
          <!-- 					<radio-group class="danxuanbtn" disabled="true" @change="changexie">
						<label style="padding-right: 30rpx;">
							<radio disabled="true" value="0" color="#2f67ff" checked="true" /><text>男</text>
						</label>
						<label>
							<radio disabled="true" value="1" color="#2f67ff"/><text>女</text>
						</label>
					</radio-group> -->
          <!-- <input v-model="username" disabled="true" placeholder="上传身份证获取性别" style="font-size: 14px;"/> -->
          <text :class="userxie != 3 ? 'myblack' : '' ">{{userxie == 1 ? '男' : userxie == 0 ? '女' : '上传身份证获取性别'}}</text>
        </view>
        <view class="info3"><input :style="phoneCorrect == false ? 'color: red;' : ''" v-model="userphone"
            placeholder="请输入联系电话" style="font-size: 14px;" /></view>
        <view class="info4"><input placeholder="上传身份证获取联系地址" disabled v-model="address" style="font-size: 14px;" />
        </view>
      </view>
      <view class="kongbai"></view>
      <view class="card-title">上传证件照信息</view>
      <view class="idcard-renzheng">
        <view class="imgandtext">
          <view class="myheadtext">头像面</view>
          <view class="myheadtips" style="color: #afafaf; font-size: 12px;">请上传身份证头像面</view>
          <view class="card-img" @click="changefontimage">
            <image :src="frontimage"></image>
          </view>
        </view>
        <view class="imgandtext">
          <view class="myheadtext">国徽面</view>
          <view class="myheadtips" style="color: #afafaf; font-size: 12px;">请上传身份证国徽面</view>
          <view class="card-img" @click="changebackimage">
            <image :src="backimage"></image>
          </view>
        </view>
      </view>
      <view class="card-num">
        <view class="text" style="font-size: 28rpx;">身份证号码</view>
        <input class="myinput1" type="text" v-model="personcode" placeholder="身份证号码" disabled="true"
          style="font-size: 24rpx; color: #999;">
      </view>
      <view class="enter-btn">
        <button @click="sub">确认</button>
      </view>
    </view>

    <!--       <view class="" style="position: fixed; top: 50%; left: 50%;">
      <button open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">shouqian</button> 
      <!--获取昵称-->
    <!-- </view> -->


  </view>
</template>

<script>
  import {
    pathToBase64,
    base64ToPath
  } from '../../../js_sdk/mmmm-image-tools/index.js'
  import myutil from '../../../common/util.js'
  export default {
    data() {
      return {
        imgpath: this.imgpath,
        imagesrc: '/static/images/355.png',
        username: '',
        userxie: 3, //0男  1女
        userphone: '',
        address: '',
        frontimage: '/static/images/427.png',
        backimage: '/static/images/idcardf.png',
        personcode: '上传身份证照片获取',
        openType: null,
        fontBool: false, // 身份证正面上传成功状态
        backBool: false, //身份证反面上传成功状态
        timer: null, //身份证上传的定时器
        outTime: 1000, //身份证上传的超时时间
        idCardFont: false,
        idCardBack: false
      }
    },
    onLoad(options) {
      if (options.openType != null) {
        this.openType = options.openType
      }
      console.log('options.openType', options.openType);
    },
    computed: {
      phoneCorrect() {
        return myutil.isPhoneNumberValid(this.userphone)
      },
    },
    methods: {
      myonChooseAvatar(e) {
        console.log(e);
      },

      onChooseAvatar(e) {
        console.log(12111111);
        console.log('e', e);

      },

      // 添加包工头
      addLabour() {
        uni.showLoading({
          title: '添加人员中...'
        })
        uni.$put(this.path + '/person/add', {
          createByDocument: uni.getStorageSync('userCode'),
          id: '',
          isHeader: 1, //被添加的人员是否为包工头 (0表示否 1表示是)	
          personAddress: this.address,
          personGroup: '',
          personIdentity: 1, //被添加人的人员身份 (0表示组长 1表示劳工)
          personIdentityCard: this.personcode,
          personName: this.username,
          personPhone: this.userphone,
          personProject: '', //人员关联项目
          personRelativeProject: '', //人员关联项目id
          personSex: this.userxie, //人员性别 (0表示女 1表示男)
          personStatus: 0, //人员状态 (0表示长期工 1表示短期工 2表示临时工)
        }).then(res => {
          console.log('添加的是包工头');
          console.log(res);
          if (res.code == 200) {
            uni.hideLoading()
            uni.showToast({
              title: '人员添加成功',
              icon: 'none'
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          } else {
            // 人员添加失败
            uni.hideLoading()
            uni.showToast({
              // title: '人员添加失败 请稍后重试',
              title: res.message,
              icon: 'none'
            })

          }
        })

      },

      // 添加劳工
      sub() {
        console.log(this.username);
        console.log(uni.getStorageSync('nickName'));
        if (this.username == uni.getStorageSync('nickName')) {
          uni.showToast({
            title: '不能自己添加自己',
            icon: 'none'
          })
          return
        }

        if (this.username.length == 0 || this.userphone.length == 0 || this.personcode.length == 0 || this.address
          .length == 0) {
          uni.showToast({
            title: '请填写完整信息后尝试',
            icon: 'none'
          })
          return
        }

        if (!this.phoneCorrect) {
          uni.showToast({
            title: '请填写正确的手机号',
            icon: 'none'
          })
          return
        }

        if (this.frontimage.indexOf('427.png') != -1) {
          uni.showToast({
            title: '请上传身份证图片',
            icon: 'none'
          })
          return
        }

        if (this.backimage.indexOf('426.png') != -1) {
          uni.showToast({
            title: '请上传身份证图片',
            icon: 'none'
          })
          return
        }

        if (!this.fontBool || !this.backBool) {
          uni.showToast({
            title: '请正确上传身份证正反面',
            icon: 'none'
          })
          return
        }

        if (!this.fontBool || !this.backBool) {
          uni.showToast({
            title: '请正确上传身份证正反面',
            icon: 'none'
          })
          return
        }

        // 是null的话就表示添加劳工
        console.log('this.openType != null', this.openType != null);
        console.log(this.openType);
        if (this.openType != 'null') {
          // 说明要添加包工头
          this.addLabour()
          return
        }

        uni.showLoading({
          title: '添加人员中...'
        })
        if (this.openType = 'null') {
          console.log('type is null');
          uni.$put(this.path + '/person/add', {
            createByDocument: uni.getStorageSync('userCode'),
            isHeader: 0, //人员是否为包工头 (0表示否 1表示是)	
            personAddress: this.address,
            personGroup: '',
            personIdentity: 1, //被添加人的人员身份 (0表示组长 1表示劳工)
            personIdentityCard: this.personcode,
            personName: this.username,
            personPhone: this.userphone,
            personProject: '', //人员关联项目
            personSex: this.userxie, //人员性别 (0表示女 1表示男)
            personStatus: 0, //人员状态 (0表示长期工 1表示短期工 2表示临时工)
          }).then(res => {
            console.log('添加劳工');
            console.log(res);
            if (res.code == 200) {
              uni.hideLoading()
              uni.showToast({
                title: '人员添加成功',
                icon: 'none'
              })
              setTimeout(() => {
                uni.navigateBack()
              }, 1000)
            } else {
              // 人员添加失败
              uni.hideLoading()
              uni.showToast({
                // title: '人员添加失败 请稍后重试',
                title: res.message,
                icon: 'none'
              })
            }

          })
        }




      },

      //选择性别
      changexie(e) {
        uni.showToast({
          title: '上传身份证自动填充',
          icon: 'none'
        })
        console.log(e);
      },

      //选着人的头像
      changeimage() {
        uni.chooseImage({
          count: 1,
          success: (res) => {
            this.imagesrc = res.tempFilePaths[0]
            pathToBase64(this.imagesrc).then(base64 => {
              // console.log(base64); 已经转换成base64了
              // console.log(base64);

            })
          },
          fail: (res) => {
            uni.showToast({
              title: res.massage,
              icon: 'none',
              duration: 500
            })
            console.log(res);
          }
        })
      },

      //点击上传身份证正面图标
      changefontimage() {

        // 如果身份证上传成功那么下一次点击就是查看大图
        if (this.fontBool) {
          // 如果上传成功了 那么下一次上传就是提示查看还是替换
          uni.showModal({
            title: '提示',
            cancelText: '查看',
            content: '查看图片还是替换图片',
            confirmText: '替换',
            success: (res) => {
              console.log(res);
              if (res.cancel != null && res.cancel == true) {
                // 点击了查看
                uni.previewImage({
                  urls: [this.frontimage]
                })
                return

              } else {
                this.setIdCardFont()
              }
            }
          })
        } else {
          // 第一次点击直接上传图片
          this.setIdCardFont()
        }


      },

      // 上传身份证正面
      setIdCardFont() {
        let token = uni.getStorageSync('token')
        let timeout = false; // 标志变量用于判断是否超时
        let _this = this

        uni.chooseImage({
          count: 1,
          success: (res) => {
            console.log('res.tempFilePaths[0]', res.tempFilePaths[0]);
            this.frontimage = res.tempFilePaths[0]
            //图片选择成功
            uni.showLoading({
              title: '图片上传中...'
            })
            uni.uploadFile({
              url: this.path + '/person/ocr',
              filePath: this.frontimage,
              name: 'file',
              timeout: 10000,
              header: {
                "Authorization": token
              },
              success: (res) => {
                // console.log('身份证上传成功的返回值',res);
                let idcode = res.data.replace(/\\+/g, '').replace(/[\t\r\f\n\s]*/g, '')
                // console.log('修正后的idcode',idcode);

                let Mymatch = idcode.match(/"content":"(.*?)","height"/)
                //只要能找到 公民身份证 这几个就是一个正确的身份证正面
                if (Mymatch[1].indexOf('公民身份号码') != -1) {
                  // 身份证识别成功
                  this.fontBool = true
                  console.log('this.fontBool', this.fontBool);
                  uni.hideLoading()
                  clearTimeout(this.timer)
                  uni.showToast({
                    title: '身份证识别成功',
                    icon: 'none',
                    duration: 1000
                  })
                  console.log('Mymatch[1]', Mymatch[1]);
                  let success = Mymatch[1].match(/公民身份号码(\d+)/)[1]
                  console.log('身份证号码 数据', success);

                  const inputString = Mymatch[1].replace(/\s/g, '');
                  // 使用正则表达式提取姓名和性别和地址
                  const addressPatten = /住址(.*?)公民身份号码/;
                  const namePattern = /姓名(.*?)性别/;
                  const genderPattern = /性别(.*?)民族/;
                  const addressMatch = inputString.match(addressPatten);
                  const nameMatch = inputString.match(namePattern);
                  const genderMatch = inputString.match(genderPattern);
                  console.log('addressMatch', addressMatch);
                  console.log('nameMatch', nameMatch);
                  console.log('genderMatch', genderMatch);
                  if (nameMatch && nameMatch[1] && genderMatch && genderMatch[1] && addressMatch &&
                    addressMatch[1]) {
                    const name = nameMatch[1];
                    const gender = genderMatch[1];
                    const address = addressMatch[1]

                    console.log("姓名: " + name);
                    console.log("性别: " + gender);
                    console.log('住址', address);
                    this.userxie = (gender === '男' ? 1 : 0)
                    console.log('this.userxie', this.userxie);
                    this.username = name
                    this.address = address
                    console.log('this.address', this.address);
                  } else {
                    uni.showToast({
                      title: '身份证图片不清晰,请重试',
                      icon: 'error'
                    })
                    this.fontBool = false
                    console.log("未找到姓名和性别字段");
                    return
                  }

                  this.personcode = success
                } else {
                  //身份证识别失败 上传
                  this.fontBool = false
                  clearTimeout(this.timer)
                  uni.hideLoading()
                  uni.showToast({
                    title: '身份证识别失败 上请重新上传',
                    icon: 'none',
                    duration: 1000
                  })

                }

              },
              fail: (err) => {
                uni.hideLoading()
                uni.showToast({
                  title: '图片上传超时 请稍后重试',
                  icon: 'error',
                })
                console.log('图片上传失败 请稍后重试', err);
              }
            })

          },
          fail: (res) => {
            uni.showToast({
              title: res.massage,
              icon: 'none',
              duration: 1000
            })
            console.log(res);
            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          }
        })

      },

      //点击身份证反面
      changebackimage() {
        // 如果身份证上传成功那么下一次点击就是查看大图
        if (this.backBool) {
          uni.showModal({
            title: '提示',
            cancelText: '查看',
            content: '查看图片还是替换图片',
            confirmText: '替换',
            success: (res) => {
              console.log(res);
              if (res.cancel != null && res.cancel == true) {
                // 点击了查看
                uni.previewImage({
                  urls: [this.backimage]
                })
                return
              } else {
                this.setIdCardBack()
              }
            }
          })
        } else {
          this.setIdCardBack()
        }
      },

      // 上传身份证反面
      setIdCardBack() {
        let token = uni.getStorageSync('token')
        uni.chooseImage({
          count: 1,
          success: (res) => {
            this.backimage = res.tempFilePaths[0]

            //图片选择成功
            uni.showLoading({
              title: '图片上传中...'
            })
            uni.uploadFile({
              url: this.path + '/person/ocr',
              filePath: this.backimage,
              name: 'file',
              timeout: 10000,
              header: {
                "Authorization": token
              },
              success: (res) => {

                // console.log('身份证上传成功的返回值',res.data);
                let idcode = res.data.replace(/\\+/g, '');
                // console.log('修正后的idcode',idcode);
                let Mymatch = idcode.match(/"content":"(.*?)","height"/)[1].replace(/\s/g, '')
                // console.log('提取中文之后的idcode',Mymatch);

                //只要能找到 中华人民共和国 这几个就是一个正确的身份证反面
                if (Mymatch.indexOf('中华人民共和国') != -1) {
                  // 身份证识别成功
                  this.backBool = true
                  console.log(' this.backBool', this.backBool);
                  uni.hideLoading()
                  uni.showToast({
                    title: '身份证识别成功',
                    icon: 'none',
                    duration: 1000
                  })
                } else {
                  //身份证识别失败 上传
                  this.backBool = false
                  uni.hideLoading()
                  uni.showToast({
                    title: '身份证识别失败 上请重新上传',
                    icon: 'none',
                    duration: 1000
                  })

                }

              },
              fail: (err) => {
                uni.hideLoading()
                uni.showToast({
                  title: '图片上传失败 请稍后重试',
                  icon: 'error',
                })
                console.log('图片上传失败 请稍后重试', err);
              }
            })


          },
          fail: (res) => {
            uni.showToast({
              title: res.massage,
              icon: 'none',
              duration: 500
            })
            console.log(res);
          }
        })
      }

    }
  }
</script>

<style lang="scss" scoped>
  .myblack {
    color: black;
  }

  .myinput1 {
    padding-left: 24rpx;

  }


  .titilename {
    position: absolute;
    top: 89rpx;
    left: 223rpx;
    font-size: 32rpx;
    color: white;

  }

  .titilephone {
    position: absolute;
    top: 142rpx;
    left: 223rpx;
    font-size: 28rpx;
    color: white;
  }

  .idcard-renzheng {
    width: 710rpx;
    margin: 0 auto;
    background-color: white;
    border-radius: 10rpx;
    display: flex;
    justify-content: space-around;
    flex-direction: column;

    .imgandtext {
      position: relative;
      width: 710rpx;
      height: 250rpx;
      margin: 0 auto;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .myheadtext {
        position: absolute;
        top: 58rpx;
        left: 20rpx;
        color: #24243F;
        font-size: 28rpx;
      }

      .myheadtips {
        position: absolute;
        z-index: 99;
        top: 106rpx;
        left: 20rpx;
        color: 24rpx;
        font-size: 24rpx;
      }

      .it-text {
        width: fit-content;
      }

      .card-img {
        position: absolute;
        top: 25rpx;
        left: 386rpx;
        width: 45%;
        height: 90%;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .color-box {
    width: 750rpx;
    height: 463rpx;
    // background: url('../../../static/images/3011.png');
    border-radius: 0 0 10px 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    // padding-bottom: 30rpx;

    .img-box {
      position: absolute;
      border-radius: 50%;
      overflow: hidden;
      top: 60rpx;
      left: 40rpx;
      width: 155rpx;
      height: 155rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .xiugai {
      margin-top: 15px;
      font-size: 14px;
      color: white;
    }
  }

  .info-pos {
    position: absolute;
    top: 259rpx;
    left: 20rpx;
    margin: 0 auto;
    background: white;
    border-radius: 16rpx;
    width: 710rpx;
    height: 477rpx;

    .base-info {
      position: absolute;
      top: 42rpx;
      left: 20rpx;
      width: 95%;
      margin: 0 auto;
      font-size: 32rpx;
    }

    .info1 {
      position: absolute;
      top: 115rpx;
      width: 670rpx;
      left: 20rpx;
    }

    .info2 {
      position: absolute;
      width: 670rpx;
      top: 215rpx;
      left: 20rpx;
      color: #888888;
      font-size: 28rpx;
      display: flex;
      justify-content: space-between;
    }

    .info3 {
      position: absolute;
      top: 315rpx;
      left: 20rpx;
      width: 670rpx;
    }

    .info4 {
      width: 670rpx;
      position: absolute;
      top: 415rpx;
      left: 20rpx;
    }



    .info {
      margin: 0 auto;
      display: flex;
      width: 95%;
      height: 40px;
      align-items: center;
      border-bottom: 1px solid #c8c8c8;
      justify-content: space-between;

      input {
        width: 100%;
        color: black;
      }

      .info-box {
        width: 80px;
        font-size: 14px;
        color: #afafaf;
      }

    }

    .danxuanbtn {
      transform: scale(0.8);
    }
  }

  .flex {
    margin-top: 10px;
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #c8c8c8;

    .danxuan {
      transform: scale(0.8);
    }
  }

  /deep/.uni-card .uni-card__header {
    border: none !important;
  }

  .kongbai {
    width: 95%;
    margin: 0 auto;
    height: 280rpx;
  }

  .card-title {
    width: 95%;
    height: 40px;
    padding-left: 17px;
    font-size: 16px;
    margin-top: 10px;
  }

  .card-num {
    width: 95%;
    margin: 0 auto;
    margin-top: 10px;
    background-color: white;
    border-radius: 10rpx;
    height: 55px;
    padding-bottom: 20rpx;

    .text {
      padding-left: 10px;
      width: 95%;
      margin: 0 auto;
      font-size: 13px;
      height: 30px;
      line-height: 30px;
    }

    .number {
      padding-left: 10px;
      width: 95%;
      margin: 0 auto;
      margin-top: 5px;
      font-size: 12px;
      color: #afafaf;
    }
  }

  .enter-btn {
    margin-top: 30px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30rpx;

    button {
      width: 80%;
      background-color: #2f67ff;
      height: 35px;
      line-height: 35px;
      color: white;
      font-size: 14px;
    }
  }
</style>
